package com.swpu.service_archive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.swpu.service_archive.entity.ArchiveBasic;
import com.swpu.service_archive.mapper.ArchiveBasicMapper;
import com.swpu.service_archive.service.ArchiveBasicService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chaichai
 * @since 2024-04-12
 */
@Service
public class ArchiveBasicServiceImpl extends ServiceImpl<ArchiveBasicMapper, ArchiveBasic> implements ArchiveBasicService {

    @Override
    public void addArchiveBasic(String openid, ArchiveBasic archiveBasic) {
        LambdaQueryWrapper<ArchiveBasic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArchiveBasic::getUserId,openid);
        ArchiveBasic basic = this.getOne(queryWrapper);
        List<Integer> habits_ = archiveBasic.getHabits_();
        String habitStr="";
        for (Integer habit : habits_) {
            if(habit==0) habitStr+=0;

            if (habit==1) {
                if(habitStr.length()>0){
                    habitStr+=",";
                }
                habitStr+='1';
            }
        }

        if(basic==null){
            archiveBasic.setUserId(openid);
            archiveBasic.setHabits(habitStr);
            this.save(archiveBasic);
        }else {
            basic.setHabits(habitStr);
            basic.setAge(archiveBasic.getAge());
            basic.setName(archiveBasic.getName());
            basic.setBloodType(archiveBasic.getBloodType());
            basic.setHeight(archiveBasic.getHeight());
            basic.setWeight(archiveBasic.getWeight());
            basic.setSex(archiveBasic.getSex());
            basic.setSportFrequency(archiveBasic.getSportFrequency());
            this.updateById(basic);
        }


    }

    @Override
    public ArchiveBasic getArchiveBasic(String openid) {
        LambdaQueryWrapper<ArchiveBasic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArchiveBasic::getUserId,openid);
        ArchiveBasic archiveBasic = this.getOne(queryWrapper);
        List<Integer> habits_=new ArrayList<>();
        String[] split = archiveBasic.getHabits().split(",");
        for (String s : split) {
            habits_.add(Integer.valueOf(s));
        }
        archiveBasic.setHabits_(habits_);
        return archiveBasic;
    }
}
